package com.zzz.servlet;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Enumeration;

/*
 * @author zzr
 * @date: 2025/07/05  20:51
 * @description: 测试 ServletConfig 和 ServletContext
 */
@WebServlet(
        urlPatterns = "/servlet1",
        initParams = {@WebInitParam(name = "keyA", value = "valueA"), @WebInitParam(name = "keyB", value = "valueB")}
)
public class servlet1 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        ServletConfig servletConfig = getServletConfig();
        // 获取初始配置信息
        // 根据参数名获取参数值
        String keyA = servletConfig.getInitParameter("keyA");
        System.out.println("keyA = " + keyA);

        // 获取所有的初始参数的名字
        Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
        // Enumeration 类似于之前的迭代器 Iterator
        // hasMoreElements：判断有没有下一个参数，如果有，返回 true，如果没有，返回 false
        // nextElement：1. 取出下一个元素 2. 向下移动游标
        while (initParameterNames.hasMoreElements()) {
            String pname = initParameterNames.nextElement();
            System.out.println(pname + " = " + servletConfig.getInitParameter(pname));
        }

    }
}
